<?php
/**
 * Extended Zend_Controller_Action Class to make some mods in init process 
 * 
 * @author Konstantin Shamko <konstantin.shamko@gmail.com> 
 * @version 0.0.1
 * @copyright  Copyright (c) 2009 Konstantin Shamko
 * @category VaselinEngine
 * @package Bel Classes
 * @license  New BSD License
 *
 */
class Bel_Controller extends Zend_Controller_Action {	
		
	/**
	 * View object (in our case it's Smarty)
	 *
	 * @var object
	 */
	public $view;	
	
	/**
	 * Seo object. Needed to set title, keywords & description to a page
	 *
	 * @var Bel_Seo
	 */
	protected $_seo;
		
	/**
	 * Messages object. Singleton to add & display messages to users
	 *
	 * @var Bel_Messages
	 */
	protected $_messages;
		
	/**
	 * Validator object. Needed for server side form validation
	 *
	 * @var Bel_Forms_Validator
	 */
	protected $_validator;
		
	/**
	 * Cache object. In our case it is Zend_Cache
	 *
	 * @var Bel_Cache
	 */
	protected $_cache;
	
	/**
     * Initialize object
     *
     * Called from {@link __construct()} as final step of object instantiation.
     *
     * @return void
     */
	public function init() {
		$this->view = Zend_Registry::get ( 'view' ); //set view
		$this->_messages = Bel_Messages::getInstance (); //set messages
		$this->_seo = Bel_Seo::getInstance (); //set seo
		$this->_cache = Zend_Registry::get ( 'cache' ); //set cache
		$this->_validator = new Bel_Forms_Validator ( ); //set validator

		$this->view->assign('module',$this->_request->getParam('module'));
		$this->view->assign('controller',$this->_request->getParam('controller'));
		$this->view->assign('action',$this->_request->getParam('action'));
	}
	
    /**
     * Redirect to another URL. If redirect happens after ajax request additional param ajax
     * is added to URL 
     *
     * Proxies to {@link Zend_Controller_Action_Helper_Redirector::gotoUrl()}.
     *
     * @param string $url
     * @param array $options Options to be used when redirecting
     * @return void
     */
	protected function _redirect($url, array $options = array()){
		if(!$this->_ifAjax()){
			parent::_redirect($url,$options);
		}else{			
			
			if(strstr($url,'?')){
				$url.='&ajax=1';
			}else{
				$url.='/?ajax=1';
			}
			
			parent::_redirect(str_replace('//','/',$url));	
		}
	}
	
	/**
	 * Detects AJAX requests
	 *
	 * @return boolean true if AJAX, false if not
	 */
	protected function _ifAjax() {
		$ajax = isset ( $_SERVER ['HTTP_X_REQUESTED_WITH'] ) ? $_SERVER ['HTTP_X_REQUESTED_WITH'] : '';
		if ($ajax == "XMLHttpRequest") {
			return true;
		}
		return false;
	}		
}